<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :http-request="upload"
      :class="{ disabled: fileComputed }"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showPercent" :percentage="percent" style="width: 180px;" />

    <!-- 弹层 -->
    <el-dialog title="图片预览" :visible.sync="showDialog">
      <img :src="imgUrl" alt="" style="width: 100%">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },

  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: '',
      showPercent: false,
      percent: 0
    }
  },

  computed: {
    fileComputed() {
      return this.fileList.length === this.limit
    }
  },

  methods: {
    // 预览图片
    preview(file) {
      this.showDialog = true
      this.imgUrl = file.url
    },

    // 删除图片
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter((item) => item.uid !== file.uid)
    },

    // 添加图片
    handleChange(file, fileList) {
      this.fileList = [...fileList]
    },

    beforeUpload(file) {
      // 图片类型
      const type = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
      if (!type.some((item) => item === file.type)) {
        this.$message.warning('上传图片只能是jpeg, jpg, png, gif格式中的一种')
        return false
      }

      const maxSize = 2 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('图片大小最大不能超过2M')
        return false
      }

      return true
    },

    // 上传
    upload(params) {
      this.showPercent = true
      const cos = new COS({
        SecretId: 'AKIDXswlJZYHjtmOkpdARQ8ZkeGbfTzEBstd',
        SecretKey: 'UhdIfla8ON6XhcHfneEXYIlxsV8amjQs'
      })

      cos.putObject(
        {
          Bucket: 'gd-1308725988', // 存储桶
          Region: 'ap-beijing', // 地域
          Key: params.file.name, // 文件名
          Body: params.file, // 要上传的文件对象
          StorageClass: 'STANDARD', // 上传的模式类型 直接默认 标准模式即可
          // 上传到腾讯云 =》 哪个存储桶 哪个地域的存储桶 文件  格式  名称 回调
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        },
        (err, data) => {
          if (!err && data.statusCode === 200) {
            // 上传成功
            this.fileList = this.fileList.map(item => {
              if (item.uid === params.file.uid) {
                return { url: 'http://' + data.Location, status: 'success' }
              }

              return item
            })
            setTimeout(() => {
              this.showPercent = false
              this.percent = 0
            }, 1000)
          }
        }
      )
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
  display: none;
}

</style>
